//
//  FMDBManager.swift
//  weibo
//
//  Created by 阿城 on 15/12/22.
//  Copyright © 2015年 阿城. All rights reserved.
//

import Foundation

class FMDBManager {
    
    static let shareManager = FMDBManager()
    
    let queue: FMDatabaseQueue
    
    var DBName = "my.db"
    
    private init(){
        var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
        path = (path as NSString).stringByAppendingPathComponent(DBName)
        queue = FMDatabaseQueue(path: path)
        
        creatTab()
    }
    
    private func creatTab(){
        
        // 1. 准备 sql
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)
        let sql = try! String(contentsOfFile: path!)
        
        // 2. 执行 sql - 内部使用了串行队列同步任务，能够保证同一时间，只有一个任务操作数据库！
        // 无论我们程序员在任何一个线程，使用 queue 操作数据库，都能够保证数据的完整性！
       queue.inTransaction { (<#FMDatabase!#>, <#UnsafeMutablePointer<ObjCBool>#>) -> Void in
        <#code#>
        }
        queue.inDatabase { (db) -> Void in
            
            if db.executeStatements(sql) {
                print("创表成功")
            } else {
                print("创表失败")
            }
        }
    }
    
    /// 查询结果的 字典数组
    func execRecordSet(sql: String) -> [[String: AnyObject]]? {
        
        var dicts: [[String: AnyObject]]?
        
        queue.inDatabase { (db) -> Void in
            
            guard let resultSet = db.executeQuery(sql) else {
                print("查询错误")
                return
            }
            
            
            while resultSet.next(){
                let num = resultSet.columnCount()
                
                for i in 0..<num{
                    let name = resultSet.columnNameForIndex(i)
                    let value = resultSet.objectForColumnIndex(i)
                    dicts?.append([name: value])
                }
            }
        }
        return dicts
    }
}